//
//  KLMModeTextField.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/11.
//

import UIKit

class KLMModeTextField: UITextField {

    private var dateFormatter: DateFormatter!
    private var initialDate: Date?
    var onDateSelected: ((Date, _ dateFormatterString: String) -> Void)?
    let leftPadding: CGFloat = 8
    
    private lazy var datePicker: UIDatePicker = {
        let picker = UIDatePicker()
        picker.datePickerMode = .dateAndTime
        if let initialDate = self.initialDate {
            picker.date = initialDate
        }
        if #available(iOS 13.4, *) {
            picker.preferredDatePickerStyle = .wheels
        }
        return picker
    }()
    private lazy var inputAccessoryToolbar: UIToolbar = {
        let toolbar = UIToolbar()
        toolbar.barStyle = .default
        toolbar.isTranslucent = true
        toolbar.tintColor = appMainThemeColor
        toolbar.sizeToFit()
        
        let cancelButton = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelDatePicker))
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(title: "确定", style: .done, target: self, action: #selector(doneDatePicker))
        
        toolbar.setItems([cancelButton, flexibleSpace, doneButton], animated: false)
        toolbar.isUserInteractionEnabled = true
        return toolbar
    }()
    
    private lazy var datePickerContainer: UIView = {
        let container = UIView()
        container.backgroundColor = .white
        
        // 设置容器高度（可自定义）
        container.frame = CGRect(x: 0, y: 0,
                                 width: UIScreen.main.bounds.width,
                                 height: self.pickerHeight)
        
        // 添加日期选择器并设置约束
        container.addSubview(datePicker)
        datePicker.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            datePicker.leadingAnchor.constraint(equalTo: container.leadingAnchor),
            datePicker.trailingAnchor.constraint(equalTo: container.trailingAnchor),
            datePicker.topAnchor.constraint(equalTo: container.topAnchor),
            datePicker.bottomAnchor.constraint(equalTo: container.bottomAnchor)
        ])
        return container
    }()
    // MARK: - 可配置属性
    var pickerHeight: CGFloat = 258 {
        didSet {
            // 更新容器高度时需要重新布局
            datePickerContainer.frame.size.height = pickerHeight
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        borderStyle = .none
        layer.cornerRadius = 4.0
        layer.masksToBounds = true
        backgroundColor = rgba(247, 247, 247, 1)
        
        textColor = rgba(38, 38, 38, 1)
        font = UIFont(safeName: "PingFangSC-Regular", size: 14)
        attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [.foregroundColor: rgba(129, 129, 129, 1)])
    }
    
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: UIEdgeInsets(top: 0, left: leftPadding, bottom: 0, right: 0))
    }
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: UIEdgeInsets(top: 0, left: leftPadding, bottom: 0, right: 0))
    }
    
    @objc private func cancelDatePicker() {
        self.resignFirstResponder()
    }
    
    @objc private func doneDatePicker() {
        let selectedDate = datePicker.date
        self.text = dateFormatter.string(from: selectedDate)
        onDateSelected?(selectedDate, text ?? "")
        self.resignFirstResponder()
    }
    
    func configKeyboard(dateFormatString: String, datePickerMode: UIDatePicker.Mode = .dateAndTime, pickerHeight: CGFloat = 258) {
        dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormatString
        dateFormatter.locale = Locale.current
        datePicker.datePickerMode = datePickerMode
        self.pickerHeight = pickerHeight
        inputView = datePickerContainer
        inputAccessoryView = inputAccessoryToolbar
    }
}
